package com.vains.config.swagger;

import com.vains.config.properties.SwaggerProperties;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestHeader;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;

/**
 * swagger3配置
 *
 * @author vains
 * @date 2021/4/5 2:36
 */
@EnableOpenApi
@Configuration
@AllArgsConstructor
public class SwaggerConfig {

    private final SwaggerProperties swaggerProperties;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
            .enable(swaggerProperties.getEnable())
            .host(swaggerProperties.getTryHost())
            .select()
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            .paths(PathSelectors.any())
            .build().apiInfo(
                new ApiInfoBuilder()
                    .title(swaggerProperties.getApplicationName() + " Restful Apis.")
                    .description(swaggerProperties.getApplicationDescription())
                    .version(swaggerProperties.getApplicationVersion())
                    .termsOfServiceUrl(swaggerProperties.getTryHost())
                    .build())
            // 忽略注解
            .ignoredParameterTypes(RequestHeader.class)
            // Bearer Token 加入 swagger
            .securitySchemes(Collections.singletonList(
                new ApiKey("Authorization", "Authorization", "header")
            ))
            .securityContexts(Collections.singletonList(
                SecurityContext.builder()
                    .securityReferences(Collections.singletonList(SecurityReference.builder()
                            .scopes(new AuthorizationScope[0])
                            .reference("Authorization")
                            .build()))
                    .operationSelector(o ->
                            o.requestMappingPattern().matches("/.*")
                    )
                    .build()
                )
            );
    }

}
